package com.tbit.uqbike.webmanager.controller;

import cn.hutool.core.util.StrUtil;
import com.tbit.uqbike.constant.MapConstant;
import com.tbit.uqbike.constant.SysConstant;
import com.tbit.uqbike.constant.UserConstant;
import com.tbit.uqbike.object.pojo.ParkPoint;
import com.tbit.uqbike.object.pojo.ParkPointApply;
import com.tbit.uqbike.object.value.LoginInfo;
import com.tbit.uqbike.object.view.JsonResult;
import com.tbit.uqbike.service.base.CalibrateService;
import com.tbit.uqbike.service.base.ParkPointService;
import com.tbit.uqbike.service.business.ParkPointApplyService;
import com.tbit.uqbike.service.business.SupportService;
import com.tbit.uqbike.webmanager.dao.core.UserDao;
import com.tbit.uqbike.webmanager.util.Assert;
import com.tbit.uqbike.webmanager.util.StringUtils;
import com.tbit.utils.DateTimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 停车点申请
 *
 * @author Leon
 * 2017年2月24日 下午5:51:05
 */
@Validated
@RestController
@RequestMapping(value = "/parkPointApply", produces = BaseController.MEDIA_JSON_UTF8)
public class ParkPointApplyController extends BaseController {
    @Autowired
    private ParkPointApplyService parkPointApplyService;
    @Autowired
    private ParkPointService parkPointService;
    @Autowired
    private CalibrateService calibrateService;
    @Autowired
    private UserDao userDao;
    @Autowired
    private SupportService supportService;
    @Autowired
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;

    /* 分页查询 */
    @RequestMapping("/queryPage")
    public JsonResult queryPage(String accountIds, String sortName,
                                @RequestParam(defaultValue = "1") Integer sign,
                                @RequestParam(defaultValue = "10") Integer rowCount,
                                @RequestParam(defaultValue = "1") Integer pageNO,
                                Integer state, Long startTime, Long endTime,
                                Integer mapType,
                                String phone,
                                HttpServletRequest request) {

        if (mapType == null) {
            mapType = SysConstant.GOOGLE;
        }
        List<Integer> accountIdList = StringUtils.str2List(accountIds, ",", true, true)
                .stream().map(Integer::parseInt).collect(Collectors.toList());
        // 获取用户信息
        LoginInfo loginInfo = getLogin(request);
        if (loginInfo.type.equals(UserConstant.USER_AGENT)) {
            accountIdList = Collections.singletonList(loginInfo.id);
        } else {
            Assert.hasLength(accountIds, "ver.accountIds.notNull");
        }
        if (sortName != null && !"".equals(sortName)) {
            sortName = sortName + (sign == 1 ? " asc" : " desc");
        }
        List<Integer> userIds = new ArrayList<>();
        /*获取总数*/
        Integer total = parkPointApplyService.queryCount(accountIdList, state, startTime, endTime, phone);
        /*当前返回行数*/
        List<ParkPointApply> parkPointApplys = parkPointApplyService.queryPage(
                accountIdList, state, startTime, endTime, rowCount, pageNO, sortName, phone);
        /*校准*/
        calibrateService.celibrateParkPointApply(parkPointApplys, mapType);

        return JsonResult.ok(parkPointApplys, total);
    }


    /* 处理 */
    @RequestMapping("/handle")
    public JsonResult handle(@NotNull(message = "ver.parkPointApplyId.notNull") Integer parkPointApplyId,
                             @NotNull(message = "ver.handleInfo.notNull") String handleInfo, Integer agree,
                             String remark, Integer accountId, String name, Integer mapType, String points, Integer distance,
                             HttpServletRequest request) {
        if (mapType == null) {
            mapType = MapConstant.MAP_GOOGLE;
        }

        //字符串长度限制
        if ((StrUtil.isNotBlank(name) && name.length() > 50) || (StrUtil.isNotBlank(handleInfo) && handleInfo.length() > 100) || (StrUtil.isNotBlank(remark) && remark.length() > 100)){
            return JsonResult.fail("参数长度超出限制", null);
        }
        LoginInfo loginInfo = getLogin(request);
        if (loginInfo.type.equals(UserConstant.USER_AGENT)) {
            accountId = loginInfo.id;
        } else {
            Assert.notNull(accountId, "ver.accountId .notNull");
        }

        if (agree == null) {
            agree = 0;
        }
        if (remark == null) {
            remark = "";
        }
        ParkPointApply parkPointApplyInDb = parkPointApplyService.getByParkPointApplyId(parkPointApplyId);
        ParkPointApply parkPointApply = new ParkPointApply();
        parkPointApply.setParkPointApplyId(parkPointApplyId);
        parkPointApply.setHandleInfo(handleInfo);
        parkPointApply.setRemark(remark);
        String nowTime = DateTimeUtil.getNowTime();
        parkPointApply.setHandleTime(nowTime);
        parkPointApply.setState(1);
        parkPointApplyService.handle(parkPointApply);

        if (distance != null) {
            final Integer accountIdFinal = accountId;
            final Integer mapTypeFinal = mapType;
            threadPoolTaskExecutor.execute(() -> {
                //需要审核通过附近未审核站点申请
                List<ParkPointApply> list = supportService.queryNearByParkPointApply(accountIdFinal, parkPointApplyInDb.getLa(), parkPointApplyInDb.getLo(), distance, mapTypeFinal);
                for (ParkPointApply pointApply : list) {
                    pointApply.setHandleTime(nowTime);
                    parkPointApplyService.handleNearBy(pointApply);
                }
            });
        }
        /**如果有代理商Id，直接自动添加停车点，误差范围默认100米*/
        if (accountId != null && agree == 1) {
            parkPointApply = parkPointApplyService.getByParkPointApplyId(parkPointApplyId);
            /**经纬度校准*/
            ParkPoint parkPoint = new ParkPoint();
            parkPoint.setAccountId(accountId);
            parkPoint.setName(name);
            parkPoint.setParkPointType(1);
            parkPoint.setLo(parkPointApply.getLo());
            parkPoint.setLa(parkPointApply.getLa());
            parkPoint.setAllowRange(100);
            parkPoint.setPoints(points);
            parkPoint.setSiteType(0);
            parkPoint.setRemark("用户申请审核通过自动创建站点");
            calibrateService.calParkPoint(parkPoint, mapType, MapConstant.MAP_ORI);
            parkPointService.insert(parkPoint, loginInfo);
        }
        return JsonResult.ok();
    }

}